<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexBlindCateRequest;
use App\Http\Requests\StoreBlindCateRequest;
use App\Http\Requests\UpdateBlindCateRequest;
use App\Http\Resources\BlindCateResource;
use App\Models\BlindCate;

class BlindCateController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(IndexBlindCateRequest $request)
    {
        $blindCate = BlindCate::query();
        if ($request->filled('name') && $request->query('name')) {
            $name = $request->query('name');
            $blindCate->where('name', 'like', '%' . $name . '%');
        }
        $blindCate->when($request->filled('status'), function ($query) use ($request) {
            return $query->where('status', $request->input('status'));
        });

        $data = $blindCate->with('statuslabel')->orderBy('order', 'ASC')->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        $response =  BlindCateResource::collection($data);
        $total = $response->total();
        return $this->success('查询成功', $response, $total);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreBlindCateRequest $request, BlindCate $blindCate)
    {
        $blindCate->fill($request->input());
        $blindCate->saveOrFail();
        return $this->success('添加盲盒分类成功', $blindCate);
    }

    /**
     * Display the specified resource.
     */
    public function show(BlindCate $blindCate, $id)
    {
        $blindCate = $blindCate->findOrFail($id);
        $this->authorize('view', $blindCate);
        $data = new BlindCateResource($blindCate->load('statuslabel'));
        return $this->success('查询成功', $data);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(BlindCate $blindCate)
    {
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateBlindCateRequest $request, BlindCate $blindCate, $id)
    {
        $blindCate = $blindCate->findOrFail($id);
        $blindCate->fill($request->input());
        $blindCate->saveOrFail();
        return $this->success('更新盲盒分类成功', $blindCate);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(BlindCate $blindCate, $id)
    {
        $shopCate = $blindCate->findOrFail($id);
        $this->authorize('delete', $blindCate);
        $shopCate->delete();
        return $this->success('删除盲盒分类成功', $shopCate);
    }
}
